package com.A1908.servlet;

import com.A1908.entity.User;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.function.DoublePredicate;

@WebServlet(urlPatterns = {"/QRServlet"})
public class QRServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String opr=req.getParameter("opr");
        PrintWriter printWriter=resp.getWriter();
        Jedis jedis = new Jedis("127.0.0.1");
        switch (opr){
            case "addSao":
                jedis.set("QRStatus", "ture");//二维码状态
                printWriter.print("success");
                break;
            case "saoVerify":
                try {
                    String QRStatus=jedis.get("QRStatus");
                    if (QRStatus.equals("ture")){
                        jedis.del("QRStatus");
                        printWriter.print("success");
                    }else {
                        printWriter.print("fail");
                    }
                } catch (Exception e) {
                    printWriter.print("fail");
                }
                break;
            case "saoAddUserInfo":
                jedis.set("username",req.getParameter("userName"));
                jedis.set("password",req.getParameter("password"));
                printWriter.print("success");
                break;
            case "saoLoginVerify":
                try {
                    String username=jedis.get("username");
                    String password=jedis.get("password");
                    jedis.del("userName");
                    jedis.del("password");
                    if (username!=null&&password!=null){
                        User user=new User();
                        user.setPhoneNumber(username);
                        user.setPassword(password);
                        printWriter.print(JSON.toJSONString(user));
                    }else {
                        printWriter.print(JSON.toJSONString("fail"));
                    }
                }catch (Exception e){
                    printWriter.print(JSON.toJSONString("fail"));
                }
                break;
        }
    }
}
